﻿#include "msgwebview.h"
#include "ui_msgwebview.h"
#include<QFile>
#include<QMessageBox>
int tcpPort=8888;
int udpPort=6666;
extern int gAccount;
msgWebView::msgWebView(int account,QWidget *parent) :
    QWidget(parent),m_account(account),
    ui(new Ui::msgWebView)
{
    ui->setupUi(this);
    setWindowFlag(Qt::FramelessWindowHint);
    loadStyleSheet();
    initTcpSocket();
    initUdpSocket();
}

void msgWebView::loadStyleSheet()
{
    QFile file(":/src/QSS/web.css");
    if(file.open(QFile::ReadOnly)){
        QString str=file.readAll();
        setStyleSheet(str);
        file.close();
    }else{
        QMessageBox::information(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("加载样式表失败!"));
    }
}

msgWebView::~msgWebView()
{
    delete ui;
}

void msgWebView::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton){
        m_point=event->globalPos()-mapToGlobal(QPoint(0,0));
        event->accept();
    }
}

void msgWebView::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons()&Qt::LeftButton){
        move(event->globalPos()-m_point);
        event->accept();
    }
}

void msgWebView::initTcpSocket()
{
    m_tcpClient=new QTcpSocket(this);
    m_tcpClient->connectToHost("127.0.0.1",tcpPort);
}

void msgWebView::initUdpSocket()
{
    m_udpReceiver = new QUdpSocket(this);
    for (quint16 i = udpPort; i < udpPort + 10; i++) {
         if (m_udpReceiver->bind(i, QUdpSocket::ShareAddress))
               break;
        }
    connect(m_udpReceiver, &QUdpSocket::readyRead, this, &msgWebView::dealData);
}

void msgWebView::on_closeBtn_clicked()
{
    close();
    emit deleteSrc();
}

void msgWebView::on_sendBtn_clicked()
{
    ui->textBrowser->appendMsg(ui->textEdit->document()->toPlainText());

    //往tcp写入数据,数据格式为:发送者的账号+接收者的账号+数据
    m_tcpClient->write((QString::number(gAccount)+QString::number(m_account)+
                       ui->textEdit->document()->toPlainText()).toUtf8());

    ui->textEdit->clear();
}

void msgWebView::dealData()
{
    if(m_udpReceiver->hasPendingDatagrams()){
        QByteArray ary;
        ary.resize(m_udpReceiver->pendingDatagramSize());
        m_udpReceiver->readDatagram(ary.data(),ary.size());
        QString ret=ary.data();
        int senderID=ret.mid(0,4).toInt();//发送者的账号
        int receiverID=ret.mid(4,4).toInt();//接受者的账号
        if(senderID==m_account&&receiverID==gAccount){
            ui->textBrowser->appendMsg(ret.mid(8),QString::number(senderID));
        }
    }
}
